const express = require('express');
const db = require('../config/db');
const router = express.Router();

// 获取操作日志列表
router.get('/logs', async (req, res) => {
  try {
    const { page = 1, pageSize = 10, startDate, endDate, userName } = req.query;
    const offset = (page - 1) * pageSize;
    
    // 管理员可以看到所有日志，普通用户只能看到自己的日志
    let query = 'SELECT id, user_id, user_name, ip_address, method, url, user_agent, request_params, response_data, status_code, duration, created_at FROM operation_logs WHERE 1=1';
    let countQuery = 'SELECT COUNT(*) as total FROM operation_logs WHERE 1=1';
    const params = [];
    
    // 如果是普通用户，只查询自己的日志
    if (req.user && req.user.role === 'user') {
      query += ' AND user_id = ?';
      countQuery += ' AND user_id = ?';
      params.push(req.user.id);
    }
    
    // 添加日期范围筛选
    if (startDate) {
      query += ' AND DATE(created_at) >= ?';
      countQuery += ' AND DATE(created_at) >= ?';
      params.push(startDate);
    }
    
    if (endDate) {
      query += ' AND DATE(created_at) <= ?';
      countQuery += ' AND DATE(created_at) <= ?';
      params.push(endDate);
    }
    
    // 添加用户名筛选
    if (userName) {
      query += ' AND user_name LIKE ?';
      countQuery += ' AND user_name LIKE ?';
      params.push(`%${userName}%`);
    }
    
    query += ' ORDER BY created_at DESC LIMIT ? OFFSET ?';
    params.push(parseInt(pageSize));
    params.push(parseInt(offset));
    
    const [rows] = await db.execute(query, params);
    const [countResult] = await db.execute(countQuery, params.slice(0, -2));
    const total = countResult[0].total;
    
    // 计算总页数
    const totalPages = Math.ceil(total / pageSize);
    
    res.json({
      code: 200,
      message: '获取操作日志成功',
      data: {
        list: rows,
        pagination: {
          currentPage: parseInt(page),
          pageSize: parseInt(pageSize),
          total: total,
          totalPages: totalPages
        }
      }
    });
  } catch (error) {
    console.error('获取操作日志失败:', error);
    res.status(500).json({
      code: 500,
      message: '服务器内部错误'
    });
  }
});

// 获取单个操作日志详情
router.get('/logs/:id', async (req, res) => {
  try {
    const { id } = req.params;
    
    let query = 'SELECT * FROM operation_logs WHERE id = ?';
    const params = [id];
    
    // 如果是普通用户，只能查看自己的日志
    if (req.user && req.user.role === 'user') {
      query += ' AND user_id = ?';
      params.push(req.user.id);
    }
    
    const [rows] = await db.execute(query, params);
    
    if (rows.length === 0) {
      return res.status(404).json({
        code: 404,
        message: '操作日志不存在或无权限查看'
      });
    }
    
    res.json({
      code: 200,
      message: '获取操作日志详情成功',
      data: rows[0]
    });
  } catch (error) {
    console.error('获取操作日志详情失败:', error);
    res.status(500).json({
      code: 500,
      message: '服务器内部错误'
    });
  }
});

module.exports = router;